package mj.scott.controller;

import com.alibaba.fastjson.JSONObject;
import mj.scott.common.Result;
import mj.scott.pojo.entity.User;
import mj.scott.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    // 微信小程序appId和secret（在微信公众平台获取）
    @Value("${wechat.appid}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;

    @Autowired
    private IUserService userService;

    @Autowired
    private RestTemplate restTemplate; // 用于调用微信接口

    /**
     * 小程序登录接口：通过code获取openid，返回用户信息
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String, String> params) {
        String code = params.get("code"); // 前端传递的临时code
        if (code == null || code.isEmpty()) {
            return Result.error("code不能为空");
        }

        // 1. 调用微信官方接口，换取openid
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" + appId +
                "&secret=" + secret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");

        if (openid == null) {
            // 微信接口返回错误（如code无效）
            String errMsg = jsonObject.getString("errmsg");
            return Result.error("登录失败：" + errMsg);
        }

        // 2. 根据openid查询或创建用户
        User user = userService.getOrCreateUser(openid);
        return Result.success(user);
    }

    /**
     * 更新用户昵称和头像（可选，用户授权后调用）
     */
    @PostMapping("/update")
    public Result<User> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success(user);
    }
}